<template>
  <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close='clear'>
    <!-- 表单区域 -->
  <el-form ref="formRef" :model="addUserform" label-width="80px" :rules="formRules">
    <el-form-item label="用户名" prop="username">
      <el-input v-model="addUserform.username"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="addUserform.password"></el-input>
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="addUserform.email"></el-input>
    </el-form-item>
    <el-form-item label="手机号" prop="mobile">
      <el-input v-model="addUserform.mobile"></el-input>
    </el-form-item>
  </el-form>
    <!-- 底部区域 -->
    <span slot="footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="confirm">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
export default {
  data: function () {
    // 验证邮箱的规则
    const checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机校验规则
    const checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      // 控制对话框的显隐
      dialogVisible: false,
      addUserform: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      formRules: {
        username: [
          { required: true, message: '请输入登录名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 监听对话框关闭事件
    clear: function () {
      this.$refs.formRef.resetFields()
    },
    // 点击确认，添加用户
    confirm: function () {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return
        const res = await this.$http.post('users', this.addUserform)
        if (res.meta.status !== 201) {
          return this.$message.warning('用户添加失败')
        }
        this.$message.success('用户添加成功！')
        this.dialogVisible = false
        this.$parent.getUserList()
      })
    }
  }
}
</script>
